<template>
  <div class="default">
    <div class='flex' style="justify-content: space-between;">
      <div>
        <el-input size="small" @blur="searchGetSupplierList" clearable v-model="params.supplierName"
                  style="width: 240px;">
          <template slot="prepend">供应商</template>
        </el-input>
      </div>
      <el-button size="small" type="primary" @click="addSupplier(null, 'add')" v-if="authorityList.includes(312)">
        新增供应商
      </el-button>
    </div>
    <el-table :data="list" border element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" class="table"
              :height="maxHeight + 'px'" v-loading='loading' tooltip-effect="dark" style="width: 100%;margin-top: 20px;"
              :header-cell-style="{  'fontSize': '14px', 'background-color': '#F3F6FD', 'color': '#333333', 'textAlign': 'center' }"
              :cellStyle="{
          'textAlign': 'center',
          'fontSize': '12px'
        }">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <div style="padding:0 30px;width:calc(100% - 300px);">
            <div style="margin-bottom: 20px;">
              <el-link type="primary" @click="oepnInputContainer('合同', scope.row.supplierId)"
                       v-if="authorityList.includes(315)">录入合同
              </el-link>
              <el-link type="success" style="margin:0 20px"
                       @click="oepnInputContainer('资质', scope.row.supplierId)" v-if="authorityList.includes(316)">录入资质
              </el-link>
              <el-link type="danger" @click="oepnInputContainer('质保金', scope.row.supplierId)"
                       v-if="authorityList.includes(317)">录入质保金
              </el-link>
            </div>
            <el-collapse :accordion="true">
              <el-collapse-item name="1">
                <template slot="title">
                  合同记录
                  <el-tooltip class="item" effect="dark" content="当前供应商合作合同上传/更新记录" placement="right">
                    <i style='margin-left: 10px;' class="el-icon-info"/>
                  </el-tooltip>
                </template>
                <el-table border :data="scope.row.supplierContractList" :headerCellStyle="{
          'textAlign': 'center',
          'fontWeight': 400
        }" :cellStyle="{
          'textAlign': 'center',
          'fontSize': '12px'
        }">
                  <el-table-column prop="contractName" label="名称"></el-table-column>
                  <el-table-column prop="createdAt" label="更新时间"></el-table-column>
                  <el-table-column prop="contractCode" label="合同编号"></el-table-column>
                  <el-table-column label="合同PDF">
                    <template slot-scope="props">
                      <el-image :src="PDFICON" style="width: 30px;cursor: pointer;"
                                @click="preViewPDF(props.row.contractImg)"></el-image>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="props">
                      <el-link type="primary" @click="deleteInfoList(props.row, 'contract')"
                               v-if="authorityList.includes(318)">删除
                      </el-link>
                      <el-link style="margin-left: 10px;" type="success"
                               @click="downLoad(props.row.contractImg)" v-if="authorityList.includes(319)">下载
                      </el-link>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
              <el-collapse-item name="2">
                <template slot="title">
                  资质记录
                  <el-tooltip class="item" effect="dark" content="当前供应商资质上传/更新记录" placement="right">
                    <i style='margin-left: 10px;' class="el-icon-info"/>
                  </el-tooltip>
                </template>
                <el-table border :data="scope.row.supplierCredentialList" :headerCellStyle="{
          'textAlign': 'center',
          'fontWeight': 400
        }" :cellStyle="{
          'textAlign': 'center',
          'fontSize': '12px'
        }">
                  <el-table-column prop="credentialName" label="名称"></el-table-column>
                  <el-table-column prop="createdAt" label="更新时间"></el-table-column>
                  <el-table-column label="资质PDF">
                    <template slot-scope="props">
                      <el-image :src="PDF2ICON" style="width: 30px;cursor: pointer;"
                                @click="preViewPDF(props.row.credentialImg)"></el-image>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="props">
                      <el-link type="primary" @click="deleteInfoList(props.row, 'credential')"
                               v-if="authorityList.includes(318)">删除
                      </el-link>
                      <el-link style="margin-left: 10px;" type="success"
                               @click="downLoad(props.row.credentialImg)" v-if="authorityList.includes(319)">下载
                      </el-link>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
              <el-collapse-item name="3">
                <template slot="title">
                  质保金
                  <el-tooltip class="item" effect="dark" content="当前供应商缴纳/扣除质保金记录" placement="right">
                    <i style='margin-left: 10px;' class="el-icon-info"/>
                  </el-tooltip>
                </template>
                <el-table border :data="scope.row.supplierWarrantyList"
                          :header-cell-style="{  'fontSize': '14px', 'background-color': '#F3F6FD', 'color': '#333333', 'textAlign': 'center' }"
                          :cellStyle="{
          'textAlign': 'center',
          'fontSize': '12px'
        }">
                  <el-table-column prop="warrantyName" label="名称"></el-table-column>
                  <el-table-column prop="warrantyMoney" label="金额"></el-table-column>
                  <el-table-column label="凭证">
                    <template slot-scope="scope">
                      <div v-if="scope.row.warrantyImgList">
                        <el-image :src="'https://'+v" ref="preview" v-for="(v, i) in scope.row.warrantyImgList" :key="i"
                                  :preview-src-list="['https://'+v]" style="width: 50px;height: 50px;"/>
                      </div>
                      <div v-else>暂无凭证</div>

                    </template>
                  </el-table-column>
                  <el-table-column prop="remark" label="备注"></el-table-column>
                  <el-table-column label="类型">
                    <template slot-scope="props">
                      <el-tag type="danger" v-if="props.row.type == 1">扣除</el-tag>
                      <el-tag v-else type="success">增加</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createdAt" label="更新时间"></el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="props">
                      <el-link type="primary" @click="deleteInfoList(props.row, 'warranty')"
                               v-if="authorityList.includes(318)">删除
                      </el-link>
                      <!-- <el-link style="margin-left: 10px;" type="success"
                        @click="downLoad(props.row.credentialImg)">下载</el-link> -->
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="合同状态" min-width="80px">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.contacrtStatus == 0">未签</el-tag>
          <el-tag type="primary" v-if="scope.row.contacrtStatus == 1">正常</el-tag>
          <el-tag type="danger" v-if="scope.row.contacrtStatus == 3">不足{{ scope.row.contacrtText }}天</el-tag>
          <el-tag type="danger" v-if="scope.row.contacrtStatus == 2">过期</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="supplierId" label="供应商ID" min-width="80px"></el-table-column>
      <el-table-column prop="supplierName" label="供应商名称" min-width="150px"></el-table-column>
      <el-table-column prop="companyName" label="公司名称" min-width="150px"></el-table-column>
      <el-table-column prop="contactPhone" label="联系电话" min-width="120px"></el-table-column>
      <el-table-column prop="accountName" label="银行" min-width="200px"></el-table-column>
      <el-table-column prop="bank" label="开户行" min-width="200px"></el-table-column>
      <el-table-column prop="bankNumber" label="卡号" min-width="200px"></el-table-column>
      <el-table-column prop="warrantyPaymentTotal" label="缴纳合计" min-width="80px"></el-table-column>
      <el-table-column prop="warrantyFineTotal" label="罚款合计" min-width="80px"></el-table-column>
      <el-table-column prop="warrantyDeposit" label="质保金结余" min-width="120px"></el-table-column>
      <el-table-column prop="remark" label="备注" min-width="140px"></el-table-column>
      <el-table-column label="合同起止日期" min-width="180px">
        <template slot-scope="scope">
          <div>开始: {{ scope.row.contactStartDate ? scope.row.contactStartDate : '暂未填写' }}</div>
          <div>截止: {{ scope.row.contactEndDate ? scope.row.contactEndDate : '暂未填写' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" min-width="100px">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
          <el-tag type='info' v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" min-width="200px"></el-table-column>
      <el-table-column fixed="right" min-width='100px' label="操作">
        <template slot-scope="scope">
          <div>
            <el-link style="color: #303e9d" @click="editSupplier(scope.row, 'edit')" v-if="authorityList.includes(313)">
              编辑
            </el-link>
          </div>
          <div>
            <el-link style="color: #303e9d" v-if="authorityList.includes(314)&&scope.row.status == 1"
                     @click="statusChange(scope.row.supplierId, 0)">禁用
            </el-link>

            <el-link style="color: #303e9d" v-if="authorityList.includes(314)&&scope.row.status == 0"
                     @click="statusChange(scope.row.supplierId, 1)">启用
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination align="center" style="margin-top: 20px;" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 30, 40, 50]"
                   layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
    </el-pagination>
    <div v-if="dialogVisible">
      <el-dialog :visible.sync="dialogVisible" width="400px" @close='close' :title="`录入供应商${inputTitle}`">
        <el-input v-if='inputTitle === "合同"' type='text' v-model="createForm.contractName">
          <template slot="prepend">合同名称</template>
        </el-input>
        <el-input v-if='inputTitle === "合同"' type='text' v-model="createForm.contractNumber" style="margin-top: 10px;">
          <template slot="prepend">合同编号</template>
        </el-input>
        <el-input v-if='inputTitle === "资质"' type='text' v-model="createForm.aptitudeName" style="margin-top: 10px;">
          <template slot="prepend">资质名称</template>
        </el-input>
        <div v-if='inputTitle === "质保金"' style="font-size: 12px;display: flex;align-items:center;margin-bottom: 10px;">
          <div style="margin-right: 10px;">类型</div>
          <el-radio-group v-model="createForm.warrantyDepositType">
            <el-radio :label="1">扣款</el-radio>
            <el-radio :label="2">缴纳</el-radio>
          </el-radio-group>
        </div>
        <el-input v-if='inputTitle === "质保金"' v-model="createForm.warrantyName">
          <template slot="prepend">名称</template>
        </el-input>
        <el-input v-if='inputTitle === "质保金"' type='number' v-model="createForm.warrantyDeposit"
                  style="margin-top: 10px;">
          <template slot="prepend">金额</template>
        </el-input>
        <el-input type='textarea' style="margin:10px 0" v-model="createForm.remark" placeholder="请输入备注"></el-input>
        <div v-if='inputTitle === "质保金"' class="uploadLine"><span style="color:red;margin-right: 5px;">*</span>质保金凭证
        </div>
        <div v-if='inputTitle === "合同"' class="uploadLine"><span style="color:red;margin-right: 5px;">*</span>上传合同PDF
        </div>
        <div v-if='inputTitle === "资质"' class="uploadLine"><span style="color:red;margin-right: 5px;">*</span>上传资质PDF
        </div>
        <div v-if="inputTitle !== '质保金'">
          <el-upload class="upload-demo" drag :headers="headers" :accept="accept" ref="upload"
                     :on-success="contractUpload" :action="`${$apiHost}`+'/img/fileImgUrl'">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em style="color: #ff6a00;">点击上传</em></div>
          </el-upload>
        </div>
        <receivedAmountUpload v-if='inputTitle === "质保金"' @clearList='clearVocherList' @url="getImageUrl"
                              btnText="选择质保金凭证"/>
        <div style="display: flex;justify-content: flex-end;margin-top: 20px;">
          <el-button type="primary" @click="submit" size="small" style="">提交</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 修改/新增供应商信息 -->
    <el-dialog :visible.sync='supplierInfoStatus' @close="close" width="600px" :title="`${supplierInfoType}供应商信息`">
      <div style="display: grid;grid-template-columns: repeat(2,1fr);grid-gap:10px;">
        <el-input clearable type='text' v-model="supplierInfo.supplierName">
          <template slot="prepend">名称</template>
        </el-input>
        <el-input clearable type='text' v-model="supplierInfo.companyName">
          <template slot="prepend">公司</template>
        </el-input>
        <el-input clearable type='text' v-model="supplierInfo.contactPhone">
          <template slot="prepend">电话</template>
        </el-input>
        <el-input clearable type='text' v-model="supplierInfo.accountName">
          <template slot="prepend">银行</template>
        </el-input>
        <el-input clearable type='text' v-model="supplierInfo.bankNumber">
          <template slot="prepend">卡号</template>
        </el-input>
        <el-input clearable type='text' v-model="supplierInfo.bank">
          <template slot="prepend">开户行</template>
        </el-input>
        <el-date-picker v-model="supplierInfo.contactStartDate" value-format="yyyy-MM-dd" style="width: 100%;"
                        type="date" placeholder="合作开始时间">
        </el-date-picker>
        <el-date-picker v-model="supplierInfo.contactEndDate" value-format="yyyy-MM-dd" style="width: 100%;" type="date"
                        placeholder="合作截止日期">
        </el-date-picker>
      </div>
      <el-input style="margin-top:10px" rows="4" type="textarea" placeholder="请输入备注"
                v-model="supplierInfo.remark"></el-input>
      <div style="display: flex;justify-content: flex-end;margin-top: 20px;">
        <el-button type="primary" @click="supplierInfoHandle" size="small" style="">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import dayjs from "dayjs";
// import pdf from 'vue-pdf'
import quinn from "../../utils/quinn";
import downloadFile from "downloadjs";
import PDFIICON from '@/assets/img/PDF.png';
import PDF2IICON from '@/assets/img/PDF2.png';
import receivedAmountUpload from '@/RayComponents/receivedAmountUpload.vue';
import Decimal from "decimal.js";
import {getOffsetDays} from '@/utils/public.js'

export default {
  name: "SupplierList",
  components: {
    // pdf
    receivedAmountUpload
  },
  data() {
    return {
      apiName: "supplierSupplierList",
      params: {
        pageSize: 20,
        pageNumber: 1,
        supplierName: ''
      },
      totalCount: 0,
      supplierInfoStatus: false,
      supplierInfoType: '新增',
      PDFICON: PDFIICON,
      PDF2ICON: PDF2IICON,
      actionUrl: '/common/upload',
      host: this.$imgHost,
      accept: '.pdf',
      depositVoucherView: [], //预览用质保金凭证
      createForm: {
        warrantyName: '',
        warrantyDeposit: 0, //质保金
        remark: '',
        depositVoucher: '', // 质保金凭证
        contractName: '',
        contractNumber: '',
        contractView: '', //合同pdf
        aptitudeName: '',
        warrantyDepositType: 0,
        aptitudeView: '', //资质pdf
      },
      supplierId: null,
      closeStatus: false,
      loading: false,
      maxHeight: 0,
      dialogVisible: false,
      pdfSrc: '',
      list: [],
      inputTitle: '',
      authorityList: [],
      currentPage: 1,
      supplierInfo: {
        supplierName: '',
        contactPhone: "",
        companyName: '',
        accountName: '',
        bank: '',
        bankNumber: '',
        remark: '',
        contactEndDate: '',
        contactStartDate: '',
      }
    }
  },
  created() {
    const {authorityList = []} = quinn.getStorage("userDatav3") || store.state.userData || {};
    this.authorityList = authorityList
    this.getSupplierList()
  },
  mounted() {
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 240;
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.maxHeight = window.innerHeight - 240;
      })
    }
  },
  computed: {
    headers() {
      return {
        token: this.tokenv3 || window.$quinn.getStorage("tokenv3"),
        warehouseId: this.warehouseId
      };
    },
  },
  methods: {
    deleteInfoList(info, type) {
      this.$alert(`确定删除ID:${info.id}的记录`, '提示', {
        confirmButtonText: '确定',
        callback: (res) => {
          if (res === 'confirm') {
            if (type == 'contract') {
              this.$api.supplierSupplierContractDelete({id: info.id}).then(async res => {
                await this.getSupplierList();
              })

            }
            if (type == 'credential') {
              this.$api.supplierSupplierCredentialDelete({id: info.id}).then(async res => {
                await this.getSupplierList();
              })
            }
            if (type == 'warranty') {
              this.$api.supplierSupplierWarrantyDelete({id: info.id}).then(async res => {
                await this.getSupplierList();
              })
            }
          }
        }
      });

    },
    clearVocherList(e) {
      if (e == 'clear') {
        this.createForm.depositVoucher = ''
      }
    },
    getImageUrl(e) {
      this.depositVoucherView = e
      if (this.depositVoucherView.length > 0) {
        this.createForm.depositVoucher = this.depositVoucherView.join(',');
      }
    },
    editSupplier(info, type) {
      this.supplierInfoStatus = true;
      this.supplierInfoType = type == 'edit' ? '修改' : '';
      this.supplierInfo.supplierId = info.supplierId;
      this.supplierInfo.supplierName = info.supplierName;
      this.supplierInfo.contactPhone = info.contactPhone;
      this.supplierInfo.companyName = info.companyName;
      this.supplierInfo.accountName = info.accountName;
      this.supplierInfo.bank = info.bank;
      this.supplierInfo.bankNumber = info.bankNumber;
      this.supplierInfo.remark = info.remark;
      this.supplierInfo.contactStartDate = info.contactStartDate
      this.supplierInfo.contactEndDate = info.contactEndDate
    },
    addSupplier(info, type) {
      this.supplierInfoStatus = true;
      this.supplierInfoType = type == 'add' ? '新增' : '';
    },
    supplierInfoHandle() {
      if (this.supplierInfoType == '新增') {
        this.$api.supplierSupplierAdd(this.supplierInfo).then(res => {
          for (let i in this.supplierInfo) {
            this.supplierInfo[i] = ''
          }
          this.supplierInfoStatus = false;
          this.getSupplierList();
        })
      } else {

        this.$api.supplierSupplierUpdate(this.supplierInfo).then(res => {
          for (let i in this.supplierInfo) {
            this.supplierInfo[i] = ''
          }
          this.supplierInfoStatus = false;
          this.getSupplierList();
        })
      }
    },
    statusChange(id, status) {
      this.$api.supplierSupplierUpdateStatus({supplierId: id, status: status}).then(async res => {
        await this.getSupplierList();
      })
    },
    handleCurrentChange(e) {
      this.params.pageNumber = e;
      this.getSupplierList()
    },
    handleSizeChange(e) {
      this.params.pageSize = e;
      this.getSupplierList()
    },
    submit() {
      // console.log(this.createForm.depositVoucher, '质保金凭证');
      // console.log(this.createForm.contractView, '合同pdf');
      // console.log(this.createForm.aptitudeView, '资质pdf');
      this.clearableStatus = false;
      if (!this.supplierId) {
        this.$message.error('请选择供应商');
        return;
      }
      if (this.inputTitle == '质保金') {
        let params = {
          type: this.createForm.warrantyDepositType,
          remark: this.createForm.remark,
          warrantyMoney: this.createForm.warrantyDeposit,
          warrantyImg: this.createForm.depositVoucher,
          supplierId: this.supplierId,
          warrantyName: this.createForm.warrantyName
        }
        this.$api.supplierAddSupplierWarranty(params).then(async res => {
          await this.inputFile();
        })
      }
      if (this.inputTitle == '合同') {
        let params = {
          contractName: this.createForm.contractName,
          contractCode: this.createForm.contractNumber,
          remark: this.createForm.remark,
          contractImg: this.createForm.contractView,
          supplierId: this.supplierId
        }
        this.$api.supplierAddSupplierContract(params).then(async res => {
          await this.inputFile();
        })
      }
      if (this.inputTitle == '资质') {
        let params = {
          credentialName: this.createForm.aptitudeName,
          remark: this.createForm.remark,
          credentialImg: this.createForm.aptitudeView,
          supplierId: this.supplierId
        }
        this.$api.supplierAddSupplierCredential(params).then(async es => {
          await this.inputFile();
        })
      }

    },
    inputFile() {
      for (let i in this.createForm) {
        this.createForm[i] = ''
      }
      this.dialogVisible = false;
      this.getSupplierList();
    },
    contractUpload(e) {
      if (this.inputTitle === '合同') this.createForm.contractView = e.result[0];
      else this.createForm.aptitudeView = e.result[0];
    },
    oepnInputContainer(type, id) {
      this.dialogVisible = true;
      this.inputTitle = type;
      this.supplierId = id
    },
    close() {
      for (let i in this.createForm) {
        this.createForm[i] = ''
      }
      for (let i in this.supplierInfo) {
        this.supplierInfo[i] = ''
      }
      this.supplierInfoStatus = false;
    },
    preViewPDF(url) {
      window.open('https://' + url);
    },
    supplierSubmit() {
      this.dialogVisible = false;
    },
    downLoad(url) {
      //  downloadFile('@/assets/demo.pdf');
      downloadFile('https://' + url)
    },
    searchGetSupplierList() {
      this.params.pageNumber = 1;
      this.getSupplierList();
    },
    getSupplierList() {
      // this.loading = true;
      this.$api[this.apiName](this.params).then(res => {
        this.list = res.rows;
        this.totalCount = res.count;
        const todayDate = dayjs().format('YYYY-MM-DD');
        this.list.map(el => {
          if (el.contactEndDate) {
            if (todayDate <= el.contactEndDate) {
              let offsetDay = getOffsetDays(todayDate, el.contactEndDate)
              if (offsetDay <= 30) {
                el.contacrtStatus = 3; //不足30天
                el.contacrtText = offsetDay;
              } else {
                el.contacrtStatus = 1; //正常
              }
            } else {
              el.contacrtStatus = 2; //过期
            }
          } else {
            el.contacrtStatus = 0; //未设置
          }
          el.warrantyDeposit = new Decimal(0).toNumber();//质保金合集
          el.warrantyFineTotal = new Decimal(0).toNumber(); //罚款总额
          el.warrantyPaymentTotal = new Decimal(0).toNumber(); //缴纳总额
          if (el.supplierWarrantyList.length == 0) return;
          el.supplierWarrantyList.map(k => {
            if (!k) return;
            if (k.warrantyImg) {
              k.warrantyImgList = k.warrantyImg.split(',');
              for (let i in k.warrantyImgList) {
                k.warrantyImgList[i] = k.warrantyImgList[i];
              }
            }
            if (k.warrantyMoney > 0) {
              if (k.type == 2) {
                el.warrantyPaymentTotal = Decimal(el.warrantyPaymentTotal).plus(Decimal(k.warrantyMoney)).toNumber();
                el.warrantyDeposit = Decimal(el.warrantyDeposit).plus(Decimal(k.warrantyMoney)).toNumber();
              } else {
                el.warrantyFineTotal = Decimal(el.warrantyFineTotal).plus(Decimal(k.warrantyMoney)).toNumber();
                el.warrantyDeposit = Decimal(el.warrantyDeposit).plus(Decimal(-k.warrantyMoney)).toNumber();
              }
            }
          })
        })
        this.loading = false;
      })
    }
  }
}
</script>
<style scoped>

@import "../../assets/css/public.css";

</style>